import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useLocalization } from '../hooks/useLocalization';

const COOKIE_CONSENT_KEY = 'daobt_cookie_consent';

const CookieConsent: React.FC = () => {
    const [isVisible, setIsVisible] = useState(false);
    const { t, getLocalizedPath } = useLocalization();

    useEffect(() => {
        try {
            const consent = localStorage.getItem(COOKIE_CONSENT_KEY);
            if (!consent) {
                setIsVisible(true);
            }
        } catch (error) {
            console.error("Could not access local storage:", error);
        }
    }, []);

    const handleAccept = () => {
        try {
            localStorage.setItem(COOKIE_CONSENT_KEY, 'true');
            setIsVisible(false);
        } catch (error) {
            console.error("Could not set item in local storage:", error);
            setIsVisible(false); // Hide banner even if storage fails
        }
    };

    if (!isVisible) {
        return null;
    }

    return (
        <div 
            className="fixed bottom-4 right-4 max-w-md w-[calc(100%-2rem)] bg-white dark:bg-gray-800 rounded-lg shadow-2xl p-5 z-[100] border border-gray-200 dark:border-gray-700"
            role="dialog"
            aria-live="polite"
            aria-label="Cookie Consent Banner"
        >
            <p className="text-gray-700 dark:text-gray-200 mb-4 text-sm">
                {t('cookie_consent_message')}
            </p>
            <div className="flex items-center justify-between gap-4">
                <Link 
                    to={getLocalizedPath('/privacy-policy')} 
                    className="text-sm text-primary dark:text-primary-light hover:underline"
                >
                    {t('privacy_policy')}
                </Link>
                <button 
                    onClick={handleAccept}
                    className="bg-primary hover:bg-primary-dark text-white font-bold py-2 px-5 rounded-md transition-colors text-sm"
                    aria-label="Accept cookie policy"
                >
                    {t('cookie_consent_accept')}
                </button>
            </div>
        </div>
    );
};

export default CookieConsent;
